<template>
  <div class="m-login">
    <van-nav-bar title="登录系统" />
    <van-form @submit="onSubmit">
      <van-cell-group inset>
        <van-field
          v-model="form.userName"
          name="userName"
          label="用户名"
          placeholder="用户名"
          :rules="[{ required: true, message: '请填写用户名' }]"
        />
        <van-field
          v-model="form.password"
          type="password"
          name="password"
          label="密码"
          placeholder="密码"
          :rules="[{ required: true, message: '请填写密码' }]"
        />
      </van-cell-group>
      <div style="margin: 16px;">
        <van-button :loading='loading' round block type="primary" native-type="submit">
          登录
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { Form, Field, CellGroup, Button, NavBar } from 'vant'
import { login } from '@/api/user.service.js'
export default {
  components: {
    [Form.name]: Form,
    [Field.name]: Field,
    [CellGroup.name]: CellGroup,
    [Button.name]: Button,
    [NavBar.name]: NavBar
  },
  data () {
    return {
      loading: false,
      form: {
        userName: '',
        password: ''
      }
    }
  },
  methods: {
    onSubmit (e) {
      this.loading = true
      login(e).then(res => {
        this.loading = false
        if (res.data.code === 0) {
          this.$router.push({
            path: '/'
          })
          // 将token存放到localStorage
          window.localStorage.setItem(process.env.VUE_APP_TOKEN_KEY, res.data.data.token)
          window.localStorage.setItem('roles', res.data.data.roles.join(','))
        }
      }).catch(() => {
        this.loading = false
      })
    }
  }
}
</script>

<style>

</style>
